<template>
  <div class="test">
    <button @click="websocketsend">发消息</button>
  </div>
</template>

<script>
export default {
  name: 'test',
  data() {
    return {
      websock: null,
      timeout: 5 * 1000,//30秒一次心跳
      timeoutObj: null,//心跳心跳倒计时
      serverTimeoutObj: null,//心跳倒计时
      timeoutnum: null,//断开 重连倒计时
      lockReconnect: false,//是否真正建立连接
    }
  },
  created() {
    this.initWebSocket();
  },
  destroyed() {
    this.websock.close() //离开路由之后断开websocket连接
  },
  methods: {
    initWebSocket() { //初始化weosocket
      const wsuri = "ws://127.0.0.1:8000";
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen() { //连接建立之后执行send方法发送数据
      this.start();
      console.log("socket连接成功")
    },
    websocketonerror() {//连接建立失败重连
      this.initWebSocket();
      console.log("连接错误")
    },
    websocketonmessage(e) { //数据接收
      const redata = JSON.parse(e.data);
      this.reset()
      console.log("数据接收", e)
    },
    websocketsend(Data) {//数据发送
      this.websock.send('是否收到前端的消息');
    },
    websocketclose(e) {  //关闭
      console.log('断开连接', e);
    },
    reconnect() {//重新连接
      var that = this;
      if (that.lockReconnect) {
        return;
      };
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum);
      that.timeoutnum = setTimeout(function () {
        //新连接
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    },
    reset() {//重置心跳
      var that = this;
      //清除时间
      clearTimeout(that.timeoutObj);
      clearTimeout(that.serverTimeoutObj);
      //重启心跳
      that.start();
    },
    start() {//开启心跳
      var that = this;
      that.timeoutObj && clearTimeout(that.timeoutObj);
      that.serverTimeoutObj && clearTimeout(that.serverTimeoutObj);
      that.timeoutObj = setTimeout(function () {
        //这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (that.websock.readyState == 1) {//如果连接正常
          that.websock.send("heartCheck");
        } else {//否则重连
          that.reconnect();
        }
        that.serverTimeoutObj = setTimeout(function () {
          //超时关闭
          that.websock.close();
        }, that.timeout);

      }, that.timeout)
    },
  },
}
</script>
<style lang='less'>
</style>
